<template>
	<div class="page-info">
		<div class="search">
			<div class="search-box">
				<a-form
					:model="searchInfo"
					:label-col="labelCol"
					:wrapper-col="wrapperCol"
				>
					<a-row :gutter="24">
						<a-col :span="6">
							<a-form-item
								:name="labelMap['eventId'].name"
								:label="labelMap['eventId'].label"
							>
								<a-select
									:placeholder="'请选择' + labelMap['eventId'].label"
									v-model:value="searchInfo.eventId"
									mode="combobox"
									style="width: 100%"
									:options="formattedOptions"
									:filter-option="filterOption"
									allow-clear
								>
								</a-select>
							</a-form-item>
						</a-col>
						<a-col :span="6">
							<a-form-item
								:name="labelMap['registrationTimeFrom'].name"
								:label="labelMap['registrationTimeFrom'].label"
							>
								<a-date-picker
									v-model:value="searchInfo.registrationTimeFrom"
								/>
							</a-form-item>
						</a-col>
						<a-col :span="6">
							<a-form-item
								:name="labelMap['registrationTimeTo'].name"
								:label="labelMap['registrationTimeTo'].label"
							>
								<a-date-picker v-model:value="searchInfo.registrationTimeTo" />
							</a-form-item>
						</a-col>
						<a-col :span="6">
							<a-form-item
								:name="labelMap['identityName'].name"
								:label="labelMap['identityName'].label"
							>
								<a-input
									style="width: 90%; margin-left: 8px"
									v-model:value="
										(searchInfo.identityVerificationVo ||= {}).name
									"
									:placeholder="'请填写' + labelMap['identityName'].label"
									allow-clear
								/>
							</a-form-item>
						</a-col>
						<a-col :span="6">
							<a-form-item
								:name="labelMap['idCardNumber'].name"
								:label="labelMap['idCardNumber'].label"
							>
								<a-input
									style="width: 90%; margin-left: 8px"
									v-model:value="
										(searchInfo.identityVerificationVo ||= {}).idCardNumber
									"
									:placeholder="'请填写' + labelMap['idCardNumber'].label"
									allow-clear
								/>
							</a-form-item>
						</a-col>
						<a-col style="text-align: right; margin-bottom: 20px">
							<a-space>
								<a-button type="primary" @click="query"> 查找</a-button>
								<a-button type="primary" @click="cancelQuery">清空</a-button>
							</a-space>
						</a-col>
					</a-row>
				</a-form>
			</div>
		</div>
		<div class="button" style="margin: 10px">
			<a-space>
				<!-- <a-button type="primary" @click="editEventRegistrationInfo('add')">新增</a-button> -->
				<a-button type="primary" @click="exportEventRegistrationInfoData()"
					>导出</a-button
				>
				<a-button type="primary" danger @click="batchDelEventRegistrationInfo"
					>删除</a-button
				>
			</a-space>
		</div>
		<div class="content">
			<a-table
				:dataSource="dataSource"
				:columns="columns"
				:loading="loading"
				:row-key="(record) => record.id"
				:pagination="pagination"
				@change="handleTableChange"
				:scroll="{ y: 470, x: 'max-content' }"
				:row-selection="rowSelection"
			>
				<template #bodyCell="{ column, record }">
					<template v-if="column.key === 'operation'">
						<a-space>
							<!-- <a-button type="primary" size="small"  
                @click="editEventRegistrationInfo('update', record.id)">编辑</a-button> -->
							<a-popconfirm
								title="确认删除?"
								ok-text="确认"
								cancel-text="取消"
								@confirm="delEventRegistrationInfo(record.id)"
								@cancel="cancel"
							>
								<a-button type="primary" size="small" danger>删除</a-button>
							</a-popconfirm>
						</a-space>
						<span></span>
					</template>
					<template v-else-if="column.key === 'gender'">
						{{
							record?.userProfileInfoVo?.gender === '0' ? '男'
							: record?.userProfileInfoVo?.gender === '1' ? '女'
							: '-'
						}}
					</template>
					<template v-else-if="column.key === 'age'">
						{{ calculateAge(record?.userProfileInfoVo?.birthYearMonth) }}
					</template>
					<template v-else-if="column.key === 'height'">
						{{ record?.userProfileInfoVo?.height || '-' }}
					</template>
					<template v-else-if="column.key === 'weight'">
						{{ record?.userProfileInfoVo?.weight || '-' }}
					</template>
					<template v-else-if="column.key === 'profession'">
						{{ record?.userProfileInfoVo?.professionName || '-' }}
					</template>
					<template v-else-if="column.key === 'income'">
						{{ record?.userProfileInfoVo?.incomeStatusName || '-' }}
					</template>
					<template v-else-if="column.key === 'region'">
						{{
							[
								record?.userProfileInfoVo?.provinceName,
								record?.userProfileInfoVo?.cityName,
								record?.userProfileInfoVo?.districtName,
							]
								.filter(Boolean)
								.join('/') || '-'
						}}
					</template>
					<template v-else-if="column.key === 'eventId'">
						<div
							style="
								width: 160px;
								white-space: nowrap;
								overflow: hidden;
								text-overflow: ellipsis;
							"
							:title="record?.datingInfoVo?.content"
						>
							{{ record?.eventInfoVo?.title }}
						</div>
					</template>
					<template v-else-if="column.key === 'code'">
						<div>{{ record?.userInfoVo?.code }}</div>
					</template>
					<template v-else-if="column.key === 'nickname'">
						<div>{{ record?.userProfileInfoVo?.nickname }}</div>
					</template>
					<template v-else-if="column.key === 'phone'">
						<div>{{ record?.userInfoVo?.phone }}</div>
					</template>
					<template v-else-if="column.key === 'identityName'">
						<div>{{ record?.identityVerificationVo?.name || '-' }}</div>
					</template>
					<template v-else-if="column.key === 'identityIdCardNumber'">
						<div>{{ record?.identityVerificationVo?.idCardNumber || '-' }}</div>
					</template>
					<template v-else-if="column.key === 'paymentAmount'">
						<div>
							{{
								record?.paymentAmount ?
									record?.paymentAmount.toFixed(2)
								:	'0.00'
							}}
						</div>
					</template>
					<template v-else-if="column.key === 'prefAge'">
						<div>
							{{
								(
									record?.userPartnerPreferencesVo?.ageFrom ||
									record?.userPartnerPreferencesVo?.ageTo
								) ?
									`${record?.userPartnerPreferencesVo?.ageFrom ?? ''}${record?.userPartnerPreferencesVo?.ageFrom || record?.userPartnerPreferencesVo?.ageTo ? '-' : ''}${record?.userPartnerPreferencesVo?.ageTo ?? ''}`
								:	'-'
							}}
						</div>
					</template>
					<template v-else-if="column.key === 'prefHeight'">
						<div>
							{{
								(
									record?.userPartnerPreferencesVo?.heightFrom ||
									record?.userPartnerPreferencesVo?.heightTo
								) ?
									`${record?.userPartnerPreferencesVo?.heightFrom ?? ''}${record?.userPartnerPreferencesVo?.heightFrom || record?.userPartnerPreferencesVo?.heightTo ? '-' : ''}${record?.userPartnerPreferencesVo?.heightTo ?? ''}`
								:	'-'
							}}
						</div>
					</template>
					<template v-else-if="column.key === 'prefWeight'">
						<div>
							{{
								(
									record?.userPartnerPreferencesVo?.weightFrom ||
									record?.userPartnerPreferencesVo?.weightTo
								) ?
									`${record?.userPartnerPreferencesVo?.weightFrom ?? ''}${record?.userPartnerPreferencesVo?.weightFrom || record?.userPartnerPreferencesVo?.weightTo ? '-' : ''}${record?.userPartnerPreferencesVo?.weightTo ?? ''}`
								:	'-'
							}}
						</div>
					</template>
					<template v-else-if="column.key === 'prefEducationLevel'">
						<div>
							{{
								record?.userPartnerPreferencesVo?.educationLevelName ||
								record?.userPartnerPreferencesVo?.educationLevel ||
								'-'
							}}
						</div>
					</template>
					<template v-else-if="column.key === 'prefProfession'">
						<div>
							{{
								record?.userPartnerPreferencesVo?.professionName ||
								record?.userPartnerPreferencesVo?.profession ||
								'-'
							}}
						</div>
					</template>
					<template v-else-if="column.key === 'prefIncomeRange'">
						<div>
							{{
								record?.userPartnerPreferencesVo?.incomeRangeName ||
								record?.userPartnerPreferencesVo?.incomeRange ||
								'-'
							}}
						</div>
					</template>
					<template v-else-if="column.key === 'prefHousingCarStatus'">
						<div>
							{{
								record?.userPartnerPreferencesVo?.housingCarStatusName ||
								record?.userPartnerPreferencesVo?.housingCarStatus ||
								'-'
							}}
						</div>
					</template>
					<template v-else-if="column.key === 'prefMaritalStatus'">
						<div>
							{{ record?.userPartnerPreferencesVo?.maritalStatusName || '-' }}
						</div>
					</template>
					<template v-else-if="column.key === 'prefRegion'">
						<div>
							{{
								(
									record?.userPartnerPreferencesVo?.provinceName ||
									record?.userPartnerPreferencesVo?.cityName ||
									record?.userPartnerPreferencesVo?.districtName
								) ?
									`${record?.userPartnerPreferencesVo?.provinceName || ''}${record?.userPartnerPreferencesVo?.cityName ? '/' + record?.userPartnerPreferencesVo?.cityName : ''}${record?.userPartnerPreferencesVo?.districtName ? '/' + record?.userPartnerPreferencesVo?.districtName : ''}`
								:	record?.userPartnerPreferencesVo?.location || '-'
							}}
						</div>
					</template>
				</template>
			</a-table>
			<EventRegistrationInfoDetail
				ref="editInfo"
				:open="visible"
				:modelInfo="modelInfo"
				@handleOk="handleOk"
				@handleCancel="handleCancel"
			></EventRegistrationInfoDetail>
		</div>
	</div>
</template>
<script setup lang="ts">
import {
	SearchInfo,
	pagination,
	columns,
	DataItem,
	ModelInfo,
	pageInfo,
} from './eventRegistrationInfoListTs';
import {
	getEventRegistrationInfoPage,
	deleteEventRegistrationInfo,
	exportEventRegistrationInfo,
} from '@/api/eventInfo/eventRegistrationInfo/eventRegistrationInfoTs';
import { message } from 'ant-design-vue';
import { getEventInfoPage } from '@/api/eventInfo/eventInfo/eventInfoTs';
import { filterOption } from '@/utils/common';
import dayjs from 'dayjs';

const labelCol = ref({ span: 5 });
const wrapperCol = ref({ span: 19 });

let rowIds = [] as any;

const rowSelection = ref({
	checkStrictly: false,
	onChange: (
		selectedRowKeys: (string | number)[],
		selectedRows: DataItem[],
	) => {
		rowIds = selectedRowKeys;
	},
	onSelect: (record: DataItem, selected: boolean, selectedRows: DataItem[]) => {
		console.log(record, selected, selectedRows);
	},
	onSelectAll: (
		selected: boolean,
		selectedRows: DataItem[],
		changeRows: DataItem[],
	) => {
		console.log(selected, selectedRows, changeRows);
	},
});

const labelMap = ref<any>({
	eventId: { name: 'eventId', label: '活动' },
	userId: { name: 'userId', label: '报名用户ID' },
	registrationTime: { name: 'registrationTime', label: '报名时间' },
	registrationTimeFrom: { name: 'registrationTimeFrom', label: '时间从' },
	registrationTimeTo: { name: 'registrationTimeTo', label: '时间到' },
	paymentStatus: {
		name: 'paymentStatus',
		label: '支付状态（0: 未支付, 1: 已支付）',
	},
	paymentAmount: {
		name: 'paymentAmount',
		label: '支付金额，用户报名时实际支付的金额',
	},
	identityName: { name: 'identityName', label: '真实姓名' },
	idCardNumber: { name: 'idCardNumber', label: '身份证号' },
});

let searchInfo = ref<SearchInfo>({ identityVerificationVo: {} as any });

const cancelQuery = (): void => {
	searchInfo.value = {};
};

const query = (): void => {
	getEventRegistrationInfoListPage(searchInfo.value, pagination.value);
};

const handleTableChange = (pagination): void => {
	getEventRegistrationInfoListPage(searchInfo.value, pagination);
};

const delEventRegistrationInfo = (ids: string): void => {
	deleteEventRegistrationInfo(ids).then((res) => {
		if (res.code == '200') {
			message.success((res && '删除' + res.message) || '删除成功！', 3);
			getEventRegistrationInfoListPage(searchInfo.value, pagination.value);
		} else {
			message.error((res && res.message) || '删除失败！', 3);
		}
	});
};

const batchDelEventRegistrationInfo = (): void => {
	let ids = '';
	if (rowIds && rowIds.length > 0) {
		rowIds.forEach((item: string) => {
			ids += item + ',';
		});
		ids = ids.substring(0, ids.length - 1);
	} else {
		message.warning('请先选择数据！', 3);
		return;
	}
	delEventRegistrationInfo(ids);
};

let loading = ref<boolean>(false);

let dataSource = ref();

const cancel = (e: MouseEvent): void => {
	console.log(e);
};

const getEventRegistrationInfoListPage = (
	param: SearchInfo,
	cur: pageInfo,
): void => {
	loading.value = true;
	getEventRegistrationInfoPage(param, cur.current, cur.pageSize)
		.then((res) => {
			if (res.code == '200') {
				dataSource.value = res.data.records;
				pagination.value.current = res.data.current;
				pagination.value.pageSize = res.data.size;
				pagination.value.total = res.data.total;
			} else {
				message.error((res && res.message) || '查询列表失败！');
			}
		})
		.finally(() => {
			loading.value = false;
		});
};

const eventList = ref<any>([]);

const getEventInfoPageInfo = () => {
	getEventInfoPage(searchInfo.value, 1, 1000).then((res) => {
		console.log(res);
		if (res.code == '200') {
			eventList.value = res?.data?.records || [];
		}
	});
};

const formattedOptions = computed(() =>
	eventList.value.map((event: any) => ({
		label: event.title, // 显示名称
		value: event.id, // 值
	})),
);

// 根据生日计算年龄
const calculateAge = (birthday: string | null | undefined): string => {
	if (!birthday) return '-';
	try {
		const birthDate = dayjs(birthday);
		const currentDate = dayjs();
		if (!birthDate.isValid()) return '-';
		const age = currentDate.diff(birthDate, 'year');
		return age >= 0 ? `${age}岁` : '-';
	} catch (error) {
		return '-';
	}
};

const exportEventRegistrationInfoData = (eventId?: number | null) => {
	exportEventRegistrationInfo({ eventId }, { responseType: 'blob' }) // 设置 responseType 为 'blob'
		.then((response) => {
			const blob = new Blob([response.data], {
				type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
			});
			const url = window.URL.createObjectURL(blob);
			const link = document.createElement('a');
			link.href = url;
			link.setAttribute('download', '用户参加活动名单.xlsx'); // 设置文件名
			document.body.appendChild(link);
			link.click();
			document.body.removeChild(link);
			window.URL.revokeObjectURL(url); // 释放内存
		})
		.catch((error) => {
			console.error('Error exporting Excel:', error);
		});
};

const init = (): void => {
	//获取活动报名表页面数据
	getEventRegistrationInfoListPage(searchInfo.value, pagination.value);
	getEventInfoPageInfo();
};

init();

let visible = ref<boolean>(false);

let modelInfo = ref<ModelInfo>({});

//新增和修改弹窗
const editEventRegistrationInfo = (type: string, id?: number): void => {
	if (type == 'add') {
		modelInfo.value.title = '新增明细';
		modelInfo.value.id = undefined;
	} else if (type == 'update') {
		modelInfo.value.title = '修改明细';
		modelInfo.value.id = id;
	}
	modelInfo.value.confirmLoading = true;
	visible.value = true;
};

const handleOk = (v: boolean): void => {
	visible.value = v;
	getEventRegistrationInfoListPage(searchInfo.value, pagination.value);
};

const handleCancel = (v: boolean): void => {
	visible.value = v;
};
</script>
<style lang="scss" scoped></style>
